<?php

namespace app\http\middleware;

use think\exception\HttpException;
use think\facade\Config;
use think\facade\Session;
use think\facade\Url;
use think\response\Json;

class Permission
{
    public function handle($request, \Closure $next)
    {
        //超级管理员不需要验证
        $user = Session::get(Config::get('user_session_key'));
        if ($user['id'] == Config::get('root_id')){
            return $next($request);
        }
        //验证权限
        $module = $request->module();
        $controller = $request->controller(true); //小写
        $action = $request->action(true); //驼峰
        $permissions = Session::get(Config::get('user_permission_key'));
        $tag = false;
        foreach ($permissions as $permission) {
            if ($permission['url'] == $module . '/' . $controller . '*' || $permission['url'] == $module . '/' . $controller . '/' . $action) {
                $tag = true;
                break;
            }
        }
        if ($tag === false) {
            if ($request->isAjax()) {
                return Json::create(['code' => 0, 'msg' => '无权限访问', 'data' => Url::build('admin/login/index')]);
            } else {
                throw new HttpException(403, '无权限访问');
            }
        }
        return $next($request);
    }
}
